package traveldream.ejb.sessionBean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import traveldream.ejb.DTO.HotelDTO;
import traveldream.ejb.entities.Hotel;
import traveldream.ejb.interfaces.HotelBeanLocal;
import traveldream.ejb.interfaces.NoDeleteException;
import traveldream.ejb.interfaces.NotFindException;

/**
 * Session Bean implementation class HotelBean
 */
@Stateless
public class HotelBean implements HotelBeanLocal {
	
	@PersistenceContext
	private EntityManager em;
    /**
     * Default constructor. 
     */
    public HotelBean() {
        // TODO Auto-generated constructor stub
    }
    
    
    
    public List<HotelDTO> getAllHotel(){
    	List<Hotel> hotels = em.createNamedQuery(Hotel.FIND_ALL).getResultList();
    	List<HotelDTO> hDTO = new ArrayList<HotelDTO>();
    	
    	for(Hotel h : hotels){
    		hDTO.add(h.convertToDTO());
    	}
    	return hDTO;
    }
    
    public HotelDTO find(int id) throws NotFindException{
    	Hotel h = em.find(Hotel.class, id);
    	try{
    		return h.convertToDTO();
    	}
    	catch(NullPointerException e){
    		throw new NotFindException();
    	}
    }

	@Override
	public void delete(int id) throws NotFindException,NoDeleteException{
		// TODO Auto-generated method stub
    	Hotel h = em.find(Hotel.class, id);
    	try{
    		for(int i=0;i<h.getDefaultPackages().size();i++){
    			if(!h.getDefaultPackages().get(i).isInvalid())
    				throw new NoDeleteException();				
    		}
    		h.setInvalid(true);
    	}
    	catch(NullPointerException e){
    		throw new NotFindException();
    	}
	}
	
}
